from rest_framework import status, mixins
from rest_framework.generics import GenericAPIView, ListAPIView, ListCreateAPIView
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.views import APIView

from meiduo_admin.serializers.users import AdminAuthSerializer, UserInfoSerializer
from users.models import User


class AdminAuthorizeView(APIView):

    def post(self, request):
        """管理员登录"""
        # 获取参数并校验
        serializer = AdminAuthSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        # 服务器生成JWT token
        # 序列化器类中没有token，所以需要重写create方法
        serializer.save()

        # 返回应答
        return Response(serializer.data, status=status.HTTP_201_CREATED)


class UserInfoView(ListCreateAPIView):
    """查询用户"""
    permission_classes = [IsAdminUser]
    serializer_class = UserInfoSerializer

    def get_queryset(self):
        keyword = self.request.query_params.get('keyword')

        if keyword:
            users = User.objects.filter(is_staff=False, username__contains=keyword)
        else:
            users = User.objects.filter(is_staff=False)
        return users

    # def get(self, request):
    #     return list(request)

        # queryset = self.get_queryset()
        #
        # serializer = UserInfoSerializer(queryset, many=True)
        #
        # return Response(serializer.data)

    # def post(self, request):
    #     """新增用户"""
    #     serializer = self.get_serializer(data=request.data)
    #     serializer.is_valid(raise_exception=True)
    #
    #     serializer.save()
    #
    #     return Response(serializer.data, status=status.HTTP_201_CREATED)


